import initPlugins from "./init";
import { config } from "../config";
import path from "path";
import { useKoaServer, useContainer } from "routing-controllers";
import { Container } from "typedi";
import { Logs } from "../utils/logs";
import { logger } from "../utils/logger";
import {LogsMiddlewares} from '../middleware/LogsMiddlewares';

export default class Start extends initPlugins {
  private app: any;

  constructor() {
    super();
    //typedi挂载到routing-controller 必须要用的时候才能挂载
    useContainer(Container);
    this.createKoa();
  }

  public createKoa() {
    this.app = useKoaServer(this.Koa2, {
      cors: true,
      validation: true,
      classTransformer: true,
      controllers: [`${path.join(__dirname, "../controller/**/*{.js,.ts}")}`],
      middlewares: [LogsMiddlewares]
    });
    this.run();
  }
  public run(): any {
    try {
      this.app.listen(config.port, () =>
        logger.logSymbolsSuccess(config.banner.welcome())
      );
    } catch (e) {
      logger.logSymbolsError(`❌ 启动出错：${e}`);
      Logs.ApplicationLogger().error(e);
    }
    this.errorCatch();
  }

  public errorCatch(): any {
    this.app.on("error", (err: { message: any }) => {
      logger.logSymbolsError(`❌ 主程序捕捉到错误：${err.message}`);
      Logs.ApplicationLogger().error(err);
    });
  }
}
